package com.firewolf.oa.base.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.firewolf.oa.base.BaseDao;

public class BaseDaoImpl<T> implements BaseDao<T> {

	@Autowired
	private SessionFactory sessionFactory;

	private Class<T> clazz = null;

	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		// 使用反射技术得到T的真实类型
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); // 获取当前new的对象的
		this.clazz = (Class<T>) pt.getActualTypeArguments()[0]; // 获取第一个类型参数的真实类型
	}

	/**
	 * 获取Session
	 * 
	 * @return
	 */
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void save(T t) {
		getSession().save(t);
	}

	@Override
	public void delete(Long id) {
		T t = getSession().get(clazz, id);
		if (t != null) {
			getSession().delete(t);
		}
	}

	@Override
	public void update(T t) {
		getSession().update(t);
	}

	@Override
	public T findById(Long id) {
		return getSession().get(clazz, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getByIds(Long[] ids) {
		return getSession().createQuery("From " + clazz.getSimpleName() + " WHERE id in (:ids)")
				.setParameterList("ids", ids).list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll() {
		return getSession().createQuery("From "+clazz.getSimpleName()).list();
	}

}
